//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.Commands
{
    using System;
    using Microsoft.Samples.ServiceBus.Messaging;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.Controllers;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels;

    public class SendMessageCommand : Command<ChatPageViewModel>
    {
        protected override bool CanExecute(ChatPageViewModel viewModel)
        {
            return viewModel != null;
        }

        protected override void Execute(ChatPageViewModel viewModel)
        {
            // Gets a Brokered Message containing the current user's name as a message property
            // and the entered text as the body.
            var message = viewModel.CurrentMessage.CreateBrokeredMessage();
            var topicClient = viewModel.TopicViewModel.TopicClient;
            var asyncState = new AsyncState { ChatPageViewModel = viewModel, TopicClient = topicClient };

            topicClient.BeginSend(message, this.OnSendMessageCompleted, asyncState);
        }

        private void OnSendMessageCompleted(IAsyncResult result)
        {
            // Retrieve the sender used to begin this async request
            var asyncState = (AsyncState)result.AsyncState;
            try
            {
                // End the send request - if the message was not sent, an exception will be thrown
                // here
                asyncState.TopicClient.EndSend(result);

                // Update the UI, clearing the value of the previously entered message and waiting 
                // for another
                ViewController.Current.BeginInvokeUI(() =>
                {
                    asyncState.ChatPageViewModel.CurrentMessage.Value = string.Empty;
                });
            }
            catch (Exception e)
            {
                App.ShowError(e);
            }
        }

        private struct AsyncState
        {
            public ChatPageViewModel ChatPageViewModel;

            public TopicClient TopicClient;
        }
    }
}
